import EmptyPape from '@/components/empty/EmptyPage';
import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useRoleState } from '@/store/roleManageStore';
import { Size } from '@/types/common';
import { Condition } from '@/types/role';
import { DownOutlined, EllipsisOutlined, RightOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, Col, Dropdown, Input, Row, Space, Table, Typography, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';
const { Text } = Typography;
import '../styles/role.scss';
import { generateUUID } from '@/utils/common';

interface Prop {
  conditions: Condition[];
  parentSize: Size;
  isAdmin: boolean;
}
const Statements = ({ conditions, parentSize, isAdmin }: Prop) => {
  const { isPc } = useWindowWidth();
  const [searchValue, setSearchValue] = useState('');
  const [loading, setLoading] = useState(false);
  const { cdtMetaData } = useRoleState();
  const textRef = useRef<HTMLDivElement>(null); // 获取文本元素的引用
  const [isTextTruncated, setIsTextTruncated] = useState(false); // 存储文本是否完全显示的状态

  const getParamName = (key: string) => {
    const param = cdtMetaData.params.find((item) => item.key == key);
    return param?.label ? `${param?.label}(${key})` : key;
  };

  const getOpName = (key: string, opStr: string) => {
    const param = cdtMetaData.params.find((item) => item.key == key);
    const type = param?.data_type;
    const ops = cdtMetaData.ops.filter((item) => item.data_type == type);
    const op = ops.find((item) => item.key == opStr);
    return op?.desc;
  };

  useEffect(() => {
    // 测量文本的实际宽度,并与容器宽度进行比较
    const checkTextTruncation = () => {
      if (textRef.current) {
        const textWidth = textRef.current.scrollWidth;
        const containerWidth = textRef.current.clientWidth;
        setIsTextTruncated(textWidth > containerWidth);
      }
    };

    // 添加事件监听器,在窗口大小变化时重新测量文本宽度
    checkTextTruncation();
    window.addEventListener('resize', checkTextTruncation);

    return () => {
      window.removeEventListener('resize', checkTextTruncation);
    };
  }, [cdtMetaData.condition_description, parentSize]);

  const columns = [
    {
      // title: <div>全部文档 ({total})</div>,
      title: (
        <div className="flex items-center">
          <div
            className={`flex flex-col ${isPc ? 'truncate' : 'whitespace-normal'}`}
            style={{ maxWidth: isPc ? `${parentSize.width * 1}px` : '100%' }}
          >
            <span className={isPc ? 'truncate' : 'whitespace-normal'}>限制规则</span>
            <span
              className={isPc ? 'truncate' : 'whitespace-normal'}
              style={{ color: '#c5c5c5', fontSize: '12px' }}
            >
              <div dangerouslySetInnerHTML={{ __html: cdtMetaData.condition_description }} />
            </span>
          </div>
          {/* {!isPc && (
            <Input
              style={{ border: 'none', background: 'transparent', color: '#C9CEE2' }}
              placeholder="搜索..."
              className="ml-4 text-sm"
              value={searchValue}
              prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
              onChange={(e) => {
                setSearchValue(e.target.value);
              }}
            />
          )} */}
        </div>
      ),
      dataIndex: 'fileInfo',
      key: 'fileInfo',
      render: (_, record: Condition) => {
        return (
          <Text
            ellipsis={{ tooltip: record.name }}
            className="ml-2"
            style={{ maxWidth: isPc ? `${parentSize.width * 0.5}px` : '100px' }}
          >
            {record.name}
          </Text>
        );
      },
      onCell: () => ({ style: { flex: '1' } }),
    },
    // {
    //   title: (
    //     <div>
    //       {isPc && (
    //         <Input
    //           style={{ border: 'none', background: 'transparent', color: '#C9CEE2' }}
    //           placeholder="搜索..."
    //           className="ml-4 text-sm"
    //           value={searchValue}
    //           prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
    //           onChange={(e) => {
    //             setSearchValue(e.target.value);
    //           }}
    //         />
    //       )}
    //     </div>
    //   ),
    //   // width: '60%',
    //   key: 'action',
    //   render: (_, record: Condition) => <div></div>,
    // },
  ];
  const style: React.CSSProperties = {
    background: '#EBEFF7',
    padding: '8px 0',
    borderRadius: '7px',
    textAlign: 'center',
  };

  return (
    <>
      <Table
        rowClassName="bg-[#F5F7FB] custom-scrollbar role-statements-table"
        className="custom-scrollbar"
        loading={loading}
        dataSource={conditions?.filter((item) => item.name.includes(searchValue))}
        columns={columns}
        pagination={false}
        rowKey={'id'}
        defaultExpandAllRows
        expandable={{
          expandedRowRender: (record) => (
            <div>
              {record.condition.map((item, index) => (
                <Row
                  key={generateUUID()}
                  className="mt-2"
                  gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}
                >
                  <Col className="gutter-row" span={8}>
                    <div style={style}>{getParamName(item.param)}</div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div style={style}>{getOpName(item.param, item.op)}</div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div style={style}>{item.value.toString()}</div>
                  </Col>
                </Row>
              ))}
            </div>
          ),
          expandIcon: ({ expanded, onExpand, record }) =>
            expanded ? (
              <DownOutlined onClick={(e) => onExpand(record, e)} />
            ) : (
              <RightOutlined onClick={(e) => onExpand(record, e)} />
            ),
          rowExpandable: (record) => record.name !== 'Not Expandable',
          columnWidth: 10,
        }}
        locale={{
          emptyText: (
            <div className="h-full" style={{ textAlign: 'center' }}>
              {!loading && <EmptyPape description="暂无数据" />}
            </div>
          ),
        }}
      ></Table>
    </>
  );
};

export default Statements;
